import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:winkai/db/database.dart';
import 'package:winkai/ext/screen_ext.dart';
import 'package:winkai/helper/user_helper.dart';
import 'package:winkai/utils/focus_utils.dart';
import 'package:winkai/utils/image_utils.dart';
import 'package:winkai/utils/smart_dialog.dart';
import 'package:winkai/widget/rounded_diagonal_path_clipper.dart';

import '../../../res/app_colors.dart';

void showNameDialog(
  BuildContext context, {
  String? nickname,
  void Function()? onComplete,
}) {
  showDialog(
      context: context,
      useSafeArea: false,
      builder: (context) {
        return Dialog(
          backgroundColor: Colors.transparent,
          insetPadding: EdgeInsets.symmetric(horizontal: 35.w),
          shape: const RoundedRectangleBorder(
            side: BorderSide.none,
            borderRadius: BorderRadius.zero,
          ),
          child: EditNameDialog(name: nickname, onComplete: onComplete),
        );
      });
}

class EditNameDialog extends StatefulWidget {
  const EditNameDialog({super.key, this.name, this.onComplete});

  final String? name;
  final void Function()? onComplete;

  @override
  State<StatefulWidget> createState() {
    return _EditNameDialogState();
  }
}

class _EditNameDialogState extends State<EditNameDialog> {
  late TextEditingController textEditingController;
  final List<String> _nicknameList = [
    'Dearest',
    'Sweetheart',
    'Baby',
    'Darling',
    'Cutie',
    'Beloved',
    'Honey',
    'Cutie',
    'Love',
  ];
  final FocusNode focusNode = FocusNode();
  static const maxLength = 20;
  bool isSend = false;

  @override
  void initState() {
    super.initState();
    textEditingController = TextEditingController(text: widget.name);
    textEditingController.addListener(_onInputChange);
    _onInputChange();
  }

  void _onInputChange() {
    isSend = textEditingController.text.toString().trim().isNotEmpty;
    setState(() {});
  }

  @override
  void dispose() {
    FocusUtils.unFocus();
    textEditingController.removeListener(_onInputChange);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    var width = screenWidth - 70.w;
    return SingleChildScrollView(
      padding: EdgeInsets.zero,
      reverse: true,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          ClipPath(
            clipper: RoundedDiagonalPathClipper(),
            child: Container(
              width: width,
              decoration: const BoxDecoration(color: Colors.white),
              clipBehavior: Clip.antiAlias,
              padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 32.w),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  SizedBox(
                    width: double.infinity,
                    child: Text(
                      'edit_name_title'.tr,
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        fontSize: 16.sp,
                        color: AppColors.color_1a,
                        fontWeight: FontWeight.w700,
                      ),
                    ),
                  ),
                  SizedBox(height: 16.w),
                  _buildInput(),
                  // SizedBox(height: 12.w),
                  // SizedBox(
                  //   width: double.infinity,
                  //   child: Text(
                  //     'edit_tips'.tr,
                  //     textAlign: TextAlign.center,
                  //     style: TextStyle(
                  //       fontSize: 14.sp,
                  //       color: Colors.black,
                  //       fontWeight: FontWeight.w600,
                  //     ),
                  //   ),
                  // ),
                  // SizedBox(height: 8.w),
                  // _buildContentWidget(),
                ],
              ),
            ),
          ),
          SizedBox(height: 20.w),
          _buildSaveWidget(),
          SizedBox(height: 16.w),
          GestureDetector(
            onTap: () {
              Get.back();
            },
            child: ImageUtils.getImage('ic_ai_eidt_user_close2', 28.w, 28.w),
          ),
        ],
      ),
    );
  }

  Widget _buildInput() {
    return Container(
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          color: const Color(0xffF8FFD9)),
      clipBehavior: Clip.antiAlias,
      child: Row(
        children: [
          Expanded(
            child: TextField(
              textInputAction: TextInputAction.done,
              onEditingComplete: _save,
              minLines: 1,
              maxLength: maxLength,
              style: TextStyle(
                height: 1,
                color: AppColors.color_1a,
                fontSize: 14.sp,
                fontWeight: FontWeight.w500,
              ),
              controller: textEditingController,
              decoration: InputDecoration(
                hintText: 'edit_input_hint'.tr,
                counterText: '',
                hintStyle: const TextStyle(color: Color(0x66000000)),
                fillColor: Colors.transparent,
                border: InputBorder.none,
                filled: true,
                isDense: true,
                contentPadding: EdgeInsets.only(
                    left: 16.w, top: 12.w, right: 10.w, bottom: 12.w),
              ),
              focusNode: focusNode,
              autofocus: true,
            ),
          ),
          if (isSend)
            GestureDetector(
                onTap: () {
                  textEditingController.text = '';
                },
                behavior: HitTestBehavior.translucent,
                child: Padding(
                  padding: EdgeInsets.all(8.w),
                  child:
                      ImageUtils.getImage('ic_ai_eidt_user_close1', 20.w, 20.w),
                )),
          SizedBox(width: 6.w),
        ],
      ),
    );
  }

  Widget _buildContentWidget() {
    var childAspectRatio = (screenWidth - 94.w) / 3 / 40.w;
    return Expanded(
      child: GridView.builder(
        physics: const BouncingScrollPhysics(),
        padding: EdgeInsets.zero,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          mainAxisSpacing: 12.w,
          crossAxisSpacing: 12.w,
          crossAxisCount: 3,
          childAspectRatio: childAspectRatio,
        ),
        itemBuilder: (context, index) {
          return _buildItem(_nicknameList[index]);
        },
        itemCount: _nicknameList.length,
      ),
    );
  }

  Widget _buildItem(String item) {
    var isSelect = textEditingController.text == item;
    return GestureDetector(
      onTap: () {
        textEditingController.text = item;
      },
      child: Container(
        width: double.infinity,
        height: 30.w,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(8),
          color: isSelect ? const Color(0xffDFFF32) : const Color(0xffFAFFE6),
        ),
        alignment: Alignment.center,
        child: Text(
          item,
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          textAlign: TextAlign.center,
          style: TextStyle(
              fontSize: 10.sp,
              color: isSelect ? Colors.black : const Color(0xb3000000),
              fontWeight: FontWeight.w500),
        ),
      ),
    );
  }

  Widget _buildSaveWidget() {
    return GestureDetector(
      onTap: _save,
      child: Container(
        width: 190.w,
        height: 50.w,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(25.w), color: Colors.black),
        child: Stack(
          alignment: Alignment.center,
          children: [
            Container(
              width: double.infinity,
              height: double.infinity,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(25.w),
                  color: isSend ? const Color(0xffDFFF32) : AppColors.color_e6),
              margin:
                  EdgeInsets.only(top: 1.w, left: 1.w, right: 1.w, bottom: 2.w),
            ),
            Text(
              'confirm'.tr,
              style: TextStyle(
                fontSize: 14.sp,
                color: Colors.black,
                fontWeight: FontWeight.w600,
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _save() {
    var nickname = textEditingController.text.toString().trim();
    if (nickname.isEmpty) {
      toast('Please enter your nickname');
      return;
    }
    if (nickname.length > maxLength) {
      toast('Enter up to $maxLength characters');
      return;
    }
    var user = UserHelper().user;
    user.nickname = nickname;
    rootDb.actDao.insertOrUpdate(deviceId: user.deviceId, nickname: nickname);
    Get.back();
    widget.onComplete?.call();
  }
}
